﻿using gt.rediscachemanager.Configuration;
using gt.rediscachemanager.Entry;
using StackExchange.Redis;
using System.Linq;
using System.Net;
using System.Text;

namespace gt.rediscachemanager.Utility
{
    public sealed class RedisClientUtility
    {
        public static string GetHostWithPort(EndPoint endPoint)
        {
            if (endPoint == null) return null;
            IPEndPoint ipPoint = endPoint as IPEndPoint;
            string host = "0";
            if (ipPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) host = ipPoint.ToString();
            //return string.Concat(host, ":", ipPoint.Port);
            return host;
        }

        public static string GetHostWithPort(EndPoint[] endPoints)
        {
            StringBuilder s = new StringBuilder();
            foreach (var ep in endPoints)
            {
                s.Append(GetHostWithPort(ep)).Append(",");
            }
            return s.ToString().TrimEnd(',');
        }

        public static string GetHostWithPort(EndPointCollection collection)
        {
            StringBuilder s = new StringBuilder();
            foreach (var ep in collection)
            {
                s.Append(GetHostWithPort(ep)).Append(",");
            }
            return s.ToString().TrimEnd(',');
        }

        private static string localIp = string.Empty;
        private static object _obj = new object();
        public static string GetLocalIp()
        {
            if (string.IsNullOrEmpty(localIp))
            {
                lock (_obj)
                {
                    if (string.IsNullOrEmpty(localIp))
                    {
                        var ipArray = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                        if (ipArray != null && ipArray.Length > 0)
                        {
                            var ip4 = ipArray.FirstOrDefault(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                            if (ip4 != null)
                            {
                                localIp = ip4.ToString();
                            }
                        }
                    }
                }
            }
            return localIp;
        }

        public static string Version
        {
            get
            {
                System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(typeof(IRedisClient));
                return a.GetName().Version.ToString(); ;
            }
        }
    }
}
